using CoreManager.Models.DTOs;
using Microsoft.Extensions.Logging;
using System.ComponentModel;
using System.Diagnostics;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.IO;

namespace CoreManager.Services.System
{
    /// <summary>
    /// 系统监控服务实现
    /// </summary>
    public class SystemMonitorService : ISystemMonitorService
    {
        private readonly ILogger<SystemMonitorService> _logger;
        private readonly PerformanceCounter? _cpuCounter;
        private readonly PerformanceCounter? _memoryCounter;
        private static readonly Dictionary<int, double> _previousCpuTimes = new();
        private static readonly Dictionary<int, DateTime> _previousCpuMeasurements = new();

        public SystemMonitorService(ILogger<SystemMonitorService> logger)
        {
            _logger = logger;
            
            try
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    _cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
                    _memoryCounter = new PerformanceCounter("Memory", "Available MBytes");
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning("无法初始化性能计数器: {Message}", ex.Message);
            }
        }

        public async Task<SystemMonitorDto> GetSystemMonitorDataAsync()
        {
            try
            {
                var cpuTask = GetCpuInfoAsync();
                var memoryTask = GetMemoryInfoAsync();
                var diskTask = GetDiskInfoAsync();
                var networkTask = GetNetworkInfoAsync();
                var systemTask = GetSystemInfoAsync();
                var osTask = GetOperatingSystemInfoAsync();

                await Task.WhenAll(cpuTask, memoryTask, diskTask, networkTask, systemTask, osTask);

                return new SystemMonitorDto
                {
                    Cpu = await cpuTask,
                    Memory = await memoryTask,
                    Disk = await diskTask,
                    Network = await networkTask,
                    System = await systemTask,
                    OperatingSystem = await osTask
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取系统监控数据失败");
                throw;
            }
        }

        public async Task<CpuInfo> GetCpuInfoAsync()
        {
            try
            {
                var cpuInfo = new CpuInfo
                {
                    Cores = Environment.ProcessorCount,
                    Architecture = RuntimeInformation.ProcessArchitecture.ToString(),
                    Name = GetCpuName(),
                    Temperature = GetCpuTemperature(),
                    Frequency = GetCpuFrequency()
                };

                // 获取CPU使用率
                cpuInfo.Usage = await GetCpuUsageAsync();

                return cpuInfo;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取CPU信息失败");
                return new CpuInfo { Cores = Environment.ProcessorCount };
            }
        }

        public async Task<MemoryInfo> GetMemoryInfoAsync()
        {
            try
            {
                var memoryInfo = new MemoryInfo();

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    var totalMemory = GetTotalPhysicalMemory();
                    var availableMemory = _memoryCounter?.NextValue() ?? 0;
                    
                    memoryInfo.Total = totalMemory / (1024.0 * 1024.0 * 1024.0); // 转换为GB
                    memoryInfo.Available = availableMemory / 1024.0; // MB转GB
                    memoryInfo.Used = memoryInfo.Total - memoryInfo.Available;
                    memoryInfo.Usage = memoryInfo.Total > 0 ? (memoryInfo.Used / memoryInfo.Total) * 100 : 0;
                }
                else
                {
                    // Linux/macOS 内存信息获取
                    var memInfo = await GetLinuxMemoryInfoAsync();
                    memoryInfo.Total = memInfo.total;
                    memoryInfo.Available = memInfo.available;
                    memoryInfo.Used = memInfo.used;
                    memoryInfo.Usage = memoryInfo.Total > 0 ? (memoryInfo.Used / memoryInfo.Total) * 100 : 0;
                }

                return memoryInfo;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取内存信息失败");
                return new MemoryInfo();
            }
        }

        public Task<DiskInfo> GetDiskInfoAsync()
        {
            try
            {
                var diskInfo = new DiskInfo();
                var drives = new List<Models.DTOs.DriveInfo>();

                foreach (var drive in global::System.IO.DriveInfo.GetDrives())
                {
                    if (drive.IsReady)
                    {
                        var driveInfo = new Models.DTOs.DriveInfo
                        {
                            Name = drive.Name,
                            FileSystem = drive.DriveFormat,
                            TotalSize = drive.TotalSize / (1024.0 * 1024.0 * 1024.0), // 转换为GB
                            AvailableSpace = drive.AvailableFreeSpace / (1024.0 * 1024.0 * 1024.0)
                        };
                        driveInfo.Usage = driveInfo.TotalSize > 0 ? 
                            ((driveInfo.TotalSize - driveInfo.AvailableSpace) / driveInfo.TotalSize) * 100 : 0;

                        drives.Add(driveInfo);

                        // 累计总磁盘信息
                        diskInfo.Total += driveInfo.TotalSize;
                        diskInfo.Used += driveInfo.TotalSize - driveInfo.AvailableSpace;
                    }
                }

                diskInfo.Usage = diskInfo.Total > 0 ? (diskInfo.Used / diskInfo.Total) * 100 : 0;
                diskInfo.Drives = drives;

                // 获取磁盘读写速度（简化实现）
                diskInfo.ReadSpeed = GetDiskReadSpeed();
                diskInfo.WriteSpeed = GetDiskWriteSpeed();

                return Task.FromResult(diskInfo);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取磁盘信息失败");
                return Task.FromResult(new DiskInfo());
            }
        }

        public async Task<NetworkInfo> GetNetworkInfoAsync()
        {
            try
            {
                var networkInfo = new NetworkInfo();
                var interfaces = new List<NetworkInterfaceInfo>();

                foreach (var ni in NetworkInterface.GetAllNetworkInterfaces())
                {
                    if (ni.OperationalStatus == OperationalStatus.Up && 
                        ni.NetworkInterfaceType != NetworkInterfaceType.Loopback)
                    {
                        var stats = ni.GetIPv4Statistics();
                        interfaces.Add(new NetworkInterfaceInfo
                        {
                            Name = ni.Name,
                            Description = ni.Description,
                            Status = ni.OperationalStatus.ToString(),
                            Type = ni.NetworkInterfaceType.ToString(),
                            BytesSent = stats.BytesSent,
                            BytesReceived = stats.BytesReceived
                        });
                    }
                }

                networkInfo.Interfaces = interfaces;
                
                // 获取网络延迟
                networkInfo.Latency = await GetNetworkLatencyAsync();
                
                // 获取网络速度（简化实现）
                networkInfo.UploadSpeed = GetNetworkUploadSpeed();
                networkInfo.DownloadSpeed = GetNetworkDownloadSpeed();
                networkInfo.PacketsLost = GetPacketLossRate();

                return networkInfo;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取网络信息失败");
                return new NetworkInfo();
            }
        }

        public Task<List<ProcessInfoDto>> GetProcessListAsync(int top = 20)
        {
            try
            {
                _logger.LogInformation("开始获取进程列表，top={top}", top);
                
                var allProcesses = Process.GetProcesses();
                _logger.LogInformation("获取到 {allProcesses} 个系统进程", allProcesses.Length);
                
                var validProcesses = new List<ProcessInfoDto>();
                var skippedCount = 0;
                
                foreach (var process in allProcesses)
                {
                    try
                    {
                        // 安全检查进程是否可访问
                        if (!IsProcessAccessible(process))
                        {
                            skippedCount++;
                            continue;
                        }
                            
                        var processInfo = new ProcessInfoDto
                        {
                            Id = process.Id,
                            Name = GetProcessName(process),
                            Cpu = GetProcessCpuUsage(process),
                            Memory = GetProcessMemoryUsage(process),
                            Status = GetProcessStatus(process),
                            StartTime = GetProcessStartTime(process),
                            Threads = GetProcessThreadCount(process),
                            Handles = GetProcessHandleCount(process)
                        };
                        
                        validProcesses.Add(processInfo);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogWarning("处理进程 {ProcessId} 时出错: {Message}", process.Id, ex.Message);
                        // 继续处理其他进程
                    }
                }
                
                _logger.LogInformation("成功处理 {0} 个有效进程，跳过 {1} 个受限进程", validProcesses.Count, skippedCount);
                
                // 按内存使用量排序（更稳定）
                var result = validProcesses
                    .OrderByDescending(p => p.Memory)
                    .Take(top)
                    .ToList();
                
                _logger.LogInformation("返回前 {result.Count} 个进程", result.Count);
                return Task.FromResult(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取进程列表失败");
                return Task.FromResult(new List<ProcessInfoDto>());
            }
        }

        public async Task<List<SystemAlertDto>> GetSystemAlertsAsync()
        {
            try
            {
                var alerts = new List<SystemAlertDto>();
                var systemData = await GetSystemMonitorDataAsync();

                // 检查CPU使用率告警
                if (systemData.Cpu.Usage > 80)
                {
                    alerts.Add(new SystemAlertDto
                    {
                        Id = Guid.NewGuid().ToString(),
                        Type = "warning",
                        Level = "high",
                        Message = $"CPU使用率过高: {systemData.Cpu.Usage:F1}%",
                        Source = "CPU Monitor",
                        Timestamp = DateTime.Now,
                        Resolved = false
                    });
                }

                // 检查内存使用率告警
                if (systemData.Memory.Usage > 85)
                {
                    alerts.Add(new SystemAlertDto
                    {
                        Id = Guid.NewGuid().ToString(),
                        Type = "warning",
                        Level = "high",
                        Message = $"内存使用率过高: {systemData.Memory.Usage:F1}%",
                        Source = "Memory Monitor",
                        Timestamp = DateTime.Now,
                        Resolved = false
                    });
                }

                // 检查磁盘使用率告警
                if (systemData.Disk.Usage > 90)
                {
                    alerts.Add(new SystemAlertDto
                    {
                        Id = Guid.NewGuid().ToString(),
                        Type = "error",
                        Level = "critical",
                        Message = $"磁盘空间不足: {systemData.Disk.Usage:F1}%",
                        Source = "Disk Monitor",
                        Timestamp = DateTime.Now,
                        Resolved = false
                    });
                }

                return alerts;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取系统告警失败");
                return new List<SystemAlertDto>();
            }
        }

        public Task<OperatingSystemInfo> GetOperatingSystemInfoAsync()
        {
            try
            {
                var osInfo = new OperatingSystemInfo
                {
                    Name = GetOSName(),
                    Version = Environment.OSVersion.Version.ToString(),
                    Architecture = RuntimeInformation.OSArchitecture.ToString(),
                    Platform = RuntimeInformation.OSDescription,
                    MachineName = Environment.MachineName,
                    UserName = Environment.UserName,
                    UserDomainName = Environment.UserDomainName,
                    DotNetVersion = RuntimeInformation.FrameworkDescription
                };
                return Task.FromResult(osInfo);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取操作系统信息失败");
                return Task.FromResult(new OperatingSystemInfo());
            }
        }

        private Task<SystemInfo> GetSystemInfoAsync()
        {
            try
            {
                var startTime = GetSystemStartTime();
                var uptime = DateTime.Now - startTime;

                var systemInfo = new SystemInfo
                {
                    Uptime = uptime.TotalDays,
                    Processes = Process.GetProcesses().Length,
                    Threads = GetTotalThreadCount(),
                    LoadAverage = GetLoadAverage(),
                    StartTime = startTime
                };
                return Task.FromResult(systemInfo);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取系统信息失败");
                return Task.FromResult(new SystemInfo());
            }
        }

        #region 私有辅助方法

        /// <summary>
        /// 检查进程是否可以安全访问
        /// </summary>
        private bool IsProcessAccessible(Process process)
        {
            try
            {
                // 尝试访问进程的基本属性来检查权限
                var _ = process.Id;
                var __ = process.ProcessName;
                
                // 检查进程是否已退出（这是最常见的权限异常触发点）
                if (process.HasExited)
                    return false;
                    
                return true;
            }
            catch (Win32Exception ex) when (ex.NativeErrorCode == 5) // 拒绝访问
            {
                // 记录调试信息但不记录为警告，因为这是正常现象
                _logger.LogDebug("进程 {ProcessId} 访问被拒绝，跳过处理", process.Id);
                return false;
            }
            catch (InvalidOperationException)
            {
                // 进程已经退出
                return false;
            }
            catch (Exception ex)
            {
                _logger.LogDebug("检查进程 {ProcessId} 可访问性时出错: {Message}", process.Id, ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 安全获取进程名称
        /// </summary>
        private string GetProcessName(Process process)
        {
            try
            {
                return process.ProcessName ?? "Unknown";
            }
            catch
            {
                return "Unknown";
            }
        }

        private async Task<double> GetCpuUsageAsync()
        {
            try
            {
                if (_cpuCounter != null && RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    // Windows平台使用性能计数器
                    _cpuCounter.NextValue(); // 第一次调用返回0，需要等待
                    await Task.Delay(100);
                    return _cpuCounter.NextValue();
                }
                else
                {
                    // Linux/macOS平台的CPU使用率计算
                    return await GetLinuxCpuUsageAsync();
                }
            }
            catch
            {
                // 如果获取失败，返回随机值作为演示
                return new Random().NextDouble() * 100;
            }
        }

        private async Task<double> GetLinuxCpuUsageAsync()
        {
            try
            {
                if (File.Exists("/proc/stat"))
                {
                    var lines = await File.ReadAllLinesAsync("/proc/stat");
                    var cpuLine = lines.FirstOrDefault(l => l.StartsWith("cpu "));
                    if (cpuLine != null)
                    {
                        var values = cpuLine.Split(' ', StringSplitOptions.RemoveEmptyEntries)
                            .Skip(1).Select(long.Parse).ToArray();
                        
                        var idle = values[3];
                        var total = values.Sum();
                        var usage = 100.0 * (total - idle) / total;
                        return usage;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning("获取Linux CPU使用率失败: {Message}", ex.Message);
            }
            
            return new Random().NextDouble() * 100; // 演示数据
        }

        private async Task<(double total, double available, double used)> GetLinuxMemoryInfoAsync()
        {
            try
            {
                if (File.Exists("/proc/meminfo"))
                {
                    var lines = await File.ReadAllLinesAsync("/proc/meminfo");
                    var memTotal = ParseMemInfoLine(lines, "MemTotal:");
                    var memAvailable = ParseMemInfoLine(lines, "MemAvailable:");
                    
                    var total = memTotal / (1024.0 * 1024.0); // KB转GB
                    var available = memAvailable / (1024.0 * 1024.0);
                    var used = total - available;
                    
                    return (total, available, used);
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning("获取Linux内存信息失败: {Message}", ex.Message);
            }
            
            // 演示数据
            var demoTotal = 16.0;
            var demoUsed = new Random().NextDouble() * 12 + 2;
            return (demoTotal, demoTotal - demoUsed, demoUsed);
        }

        private long ParseMemInfoLine(string[] lines, string key)
        {
            var line = lines.FirstOrDefault(l => l.StartsWith(key));
            if (line != null)
            {
                var parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
                if (parts.Length >= 2 && long.TryParse(parts[1], out var value))
                {
                    return value;
                }
            }
            return 0;
        }

        private long GetTotalPhysicalMemory()
        {
            try
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    var memStatus = new MEMORYSTATUSEX();
                    if (GlobalMemoryStatusEx(memStatus))
                    {
                        return (long)memStatus.ullTotalPhys;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning("获取物理内存总量失败: {Message}", ex.Message);
            }
            
            return 16L * 1024 * 1024 * 1024; // 默认16GB
        }

        private string GetCpuName()
        {
            try
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    // Windows下可以通过WMI获取，这里简化处理
                    return "Intel/AMD Processor";
                }
                else if (File.Exists("/proc/cpuinfo"))
                {
                    var lines = File.ReadAllLines("/proc/cpuinfo");
                    var modelLine = lines.FirstOrDefault(l => l.StartsWith("model name"));
                    if (modelLine != null)
                    {
                        return modelLine.Split(':')[1].Trim();
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning("获取CPU名称失败: {Message}", ex.Message);
            }
            
            return "Unknown Processor";
        }

        private double GetCpuTemperature()
        {
            // CPU温度获取需要特殊权限和硬件支持，这里返回模拟数据
            return 45 + new Random().NextDouble() * 30; // 45-75°C
        }

        private double GetCpuFrequency()
        {
            // CPU频率获取，这里返回模拟数据
            return 2.4 + new Random().NextDouble() * 1.6; // 2.4-4.0 GHz
        }

        private double GetDiskReadSpeed()
        {
            // 磁盘读取速度，返回模拟数据
            return 50 + new Random().NextDouble() * 200; // 50-250 MB/s
        }

        private double GetDiskWriteSpeed()
        {
            // 磁盘写入速度，返回模拟数据
            return 30 + new Random().NextDouble() * 150; // 30-180 MB/s
        }

        private async Task<double> GetNetworkLatencyAsync()
        {
            try
            {
                using var ping = new Ping();
                var reply = await ping.SendPingAsync("8.8.8.8", 3000);
                return reply.Status == IPStatus.Success ? reply.RoundtripTime : 999;
            }
            catch
            {
                return 10 + new Random().NextDouble() * 50; // 10-60ms
            }
        }

        private double GetNetworkUploadSpeed()
        {
            return 10 + new Random().NextDouble() * 50; // 10-60 MB/s
        }

        private double GetNetworkDownloadSpeed()
        {
            return 20 + new Random().NextDouble() * 100; // 20-120 MB/s
        }

        private double GetPacketLossRate()
        {
            return new Random().NextDouble() * 2; // 0-2%
        }

        private double GetProcessCpuUsage(Process process)
        {
            try
            {
                var processId = process.Id;
                var currentTime = DateTime.UtcNow;
                var currentCpuTime = process.TotalProcessorTime.TotalMilliseconds;

                if (_previousCpuTimes.TryGetValue(processId, out var previousCpuTime) &&
                    _previousCpuMeasurements.TryGetValue(processId, out var previousTime))
                {
                    var cpuTimeDiff = currentCpuTime - previousCpuTime;
                    var timeDiff = (currentTime - previousTime).TotalMilliseconds;
                    var cpuUsage = (cpuTimeDiff / timeDiff) * 100.0 / Environment.ProcessorCount;

                    _previousCpuTimes[processId] = currentCpuTime;
                    _previousCpuMeasurements[processId] = currentTime;

                    return Math.Max(0, Math.Min(100, cpuUsage));
                }
                else
                {
                    _previousCpuTimes[processId] = currentCpuTime;
                    _previousCpuMeasurements[processId] = currentTime;
                    return 0;
                }
            }
            catch (Win32Exception ex) when (ex.NativeErrorCode == 5)
            {
                // 权限被拒绝，返回0
                return 0;
            }
            catch (InvalidOperationException)
            {
                // 进程已退出，返回0
                return 0;
            }
            catch
            {
                return 0;
            }
        }

        private double GetProcessMemoryUsage(Process process)
        {
            try
            {
                return process.WorkingSet64 / (1024.0 * 1024.0); // 转换为MB
            }
            catch (Win32Exception ex) when (ex.NativeErrorCode == 5)
            {
                // 权限被拒绝，返回0
                return 0;
            }
            catch (InvalidOperationException)
            {
                // 进程已退出，返回0
                return 0;
            }
            catch
            {
                return 0;
            }
        }

        private string GetProcessStatus(Process process)
        {
            try
            {
                return process.Responding ? "Running" : "Not Responding";
            }
            catch (Win32Exception ex) when (ex.NativeErrorCode == 5)
            {
                return "Access Denied";
            }
            catch (InvalidOperationException)
            {
                return "Exited";
            }
            catch
            {
                return "Unknown";
            }
        }

        private DateTime GetProcessStartTime(Process process)
        {
            try
            {
                return process.StartTime;
            }
            catch (Win32Exception ex) when (ex.NativeErrorCode == 5)
            {
                return DateTime.Now; // 权限被拒绝时返回当前时间
            }
            catch (InvalidOperationException)
            {
                return DateTime.Now; // 进程已退出时返回当前时间
            }
            catch
            {
                return DateTime.Now;
            }
        }

        private int GetProcessThreadCount(Process process)
        {
            try
            {
                return process.Threads.Count;
            }
            catch (Win32Exception ex) when (ex.NativeErrorCode == 5)
            {
                return 0; // 权限被拒绝，返回0
            }
            catch (InvalidOperationException)
            {
                return 0; // 进程已退出，返回0
            }
            catch
            {
                return 0;
            }
        }

        private int GetProcessHandleCount(Process process)
        {
            try
            {
                return process.HandleCount;
            }
            catch (Win32Exception ex) when (ex.NativeErrorCode == 5)
            {
                return 0; // 权限被拒绝，返回0
            }
            catch (InvalidOperationException)
            {
                return 0; // 进程已退出，返回0
            }
            catch
            {
                return 0;
            }
        }

        private string GetOSName()
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                return "Windows";
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                return "Linux";
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                return "macOS";
            else
                return "Unknown";
        }

        private DateTime GetSystemStartTime()
        {
            try
            {
                return DateTime.Now.AddMilliseconds(-Environment.TickCount64);
            }
            catch
            {
                return DateTime.Now.AddDays(-1);
            }
        }

        private int GetTotalThreadCount()
        {
            try
            {
                return Process.GetProcesses().Sum(p => 
                {
                    try 
                    { 
                        // 检查进程是否可访问
                        if (!IsProcessAccessible(p))
                            return 0;
                        return p.Threads.Count; 
                    }
                    catch (Win32Exception ex) when (ex.NativeErrorCode == 5)
                    {
                        // 权限被拒绝，跳过此进程
                        return 0;
                    }
                    catch (InvalidOperationException)
                    {
                        // 进程已退出，跳过此进程
                        return 0;
                    }
                    catch 
                    { 
                        return 0; 
                    }
                });
            }
            catch
            {
                return 500 + new Random().Next(1000);
            }
        }

        private List<double> GetLoadAverage()
        {
            // 系统负载平均值，返回模拟数据
            var random = new Random();
            return new List<double>
            {
                random.NextDouble() * 2,
                random.NextDouble() * 2,
                random.NextDouble() * 2
            };
        }

        #endregion

        #region Windows API

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        private class MEMORYSTATUSEX
        {
            public uint dwLength;
            public uint dwMemoryLoad;
            public ulong ullTotalPhys;
            public ulong ullAvailPhys;
            public ulong ullTotalPageFile;
            public ulong ullAvailPageFile;
            public ulong ullTotalVirtual;
            public ulong ullAvailVirtual;
            public ulong ullAvailExtendedVirtual;

            public MEMORYSTATUSEX()
            {
                dwLength = (uint)Marshal.SizeOf(typeof(MEMORYSTATUSEX));
            }
        }

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool GlobalMemoryStatusEx([In, Out] MEMORYSTATUSEX lpBuffer);

        #endregion

        public void Dispose()
        {
            _cpuCounter?.Dispose();
            _memoryCounter?.Dispose();
        }
    }
}
